package cn.cas.mango.controller;

import cn.cas.mango.dto.param.AggParam;
import cn.cas.mango.dto.param.GlobalParam;
import cn.cas.mango.dto.param.News;
import cn.cas.mango.service.Agg;
import cn.cas.mango.service.PrintJson;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
@ResponseBody
@CrossOrigin
public class Temp {
  @Autowired
  private PrintJson printJson;
  @Autowired
  private Agg agg;

  @RequestMapping(value = "/es", method = {RequestMethod.GET, RequestMethod.POST})
  void tran2es(GlobalParam globalParam) throws IOException {
    printJson.main(globalParam);
  }

  @RequestMapping(value = "/agg", method = {RequestMethod.GET, RequestMethod.POST})
  JSONObject agg(AggParam aggParam)  {
    return agg.agg(aggParam);
  }

  @RequestMapping(value = "/getall", method = {RequestMethod.GET, RequestMethod.POST})
  JSONArray get(AggParam aggParam)  {
    return agg.get(aggParam);
  }

  @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST})
  JSONArray getOne(AggParam aggParam) {
    List<Hit<News>> one = agg.getOne(aggParam);
    JSONArray jsonArray = new JSONArray();
    for (Hit<News> hit: one) {
      News news = hit.source();
      JSONObject jsonObject = new JSONObject();
      assert news != null;
      jsonObject.put("title", news.getNewsTitleZh());
      jsonObject.put("content", news.getNewsContentZh());
      if (aggParam.getKeywords() != null && aggParam.getKeywords())
        jsonObject.put("keywords", news.getNewsKeywords());
      jsonObject.put("news_website", news.getNewsWebsite());
      jsonArray.add(jsonObject);
    }
    return jsonArray;
  }
}
